package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.zzyl.common.utils.SecurityUtils.getLoginUser;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isExclude() {
        String requestURI = request.getRequestURI();
        if(requestURI.startsWith("/member")) {
            return true;
        }
        return false;
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        // 插入时自动填充
        this.strictInsertFill(metaObject, "createTime" , Date.class, new Date());
        if(!isExclude()) {
            this.strictInsertFill(metaObject, "createBy" , String.class, String.valueOf(loadUserId()));
            // 同时填充更新字段（首次创建时更新时间和创建时间相同）
            this.strictInsertFill(metaObject, "updateTime" , Date.class, new Date());
            this.strictInsertFill(metaObject, "updateBy" , String.class, String.valueOf(loadUserId()));
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时自动填充（使用 strictUpdateFill）
        this.strictUpdateFill(metaObject, "updateTime" , Date.class, new Date());
        if(!isExclude()) {
            this.strictUpdateFill(metaObject, "updateBy" , String.class, String.valueOf(loadUserId()));
        }
    }

    /**
     * 获取当前登录人的ID
     *
     * @return 登录人ID
     */
    public Long loadUserId() {
        try {
            LoginUser loginUser = getLoginUser();
            if (loginUser != null) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }
}
